package org.octopus.lee.provider;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import org.octopus.lee.service.RegistryService;
import org.octopus.lee.service.impl.RegisterServiceImpl;

/**
 * Created by UCMED on 2017/1/13.
 */
public class DubboReferenceApi {
    private static final String APPLICATION_NAME_PREFIX = "Serv_";
    private String organization;
    private String address;
    private Integer protocolPort;
    private Integer protocolThreads;

    public String getOrganization() {
        return organization;
    }

    public void setOrganization(String organization) {
        this.organization = organization;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getProtocolPort() {
        return protocolPort;
    }

    public void setProtocolPort(Integer protocolPort) {
        this.protocolPort = protocolPort;
    }

    public Integer getProtocolThreads() {
        return protocolThreads;
    }

    public void setProtocolThreads(Integer protocolThreads) {
        this.protocolThreads = protocolThreads;
    }

    public <S, I> void export(Class<S> S, Class<I> I, String group) throws IllegalAccessException, InstantiationException {

        S implementService = (S) I.newInstance();
//        RegistryService r = new RegisterServiceImpl();

        // 当前应用配置
        ApplicationConfig application = new ApplicationConfig();
        application.setName(APPLICATION_NAME_PREFIX + group);
        application.setOrganization(organization);
        application.setOwner(organization);

        // 连接注册中心配置
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(address);

        // 服务提供者协议配置
        ProtocolConfig protocolConfig = new ProtocolConfig();
//        protocolConfig.setName("lyjdubbo");
        protocolConfig.setPort(protocolPort);
        protocolConfig.setThreads(protocolThreads);

        // 注意：ServiceConfig为重对象，内部封装了与注册中心的连接，以及开启服务端口

        // 服务提供者暴露服务配置
        ServiceConfig<S> serviceConfig = new ServiceConfig<S>(); // 此实例很重，封装了与注册中心的连接，请自行缓存，否则可能造成内存和连接泄漏
        serviceConfig.setApplication(application);
        serviceConfig.setRegistry(registryConfig);
        serviceConfig.setProtocol(protocolConfig);
        serviceConfig.setInterface(S);
        serviceConfig.setRef(implementService);
        serviceConfig.setVersion("1.0.0");
        serviceConfig.setGroup(group);

        // 暴露及注册服务
        serviceConfig.export();
    }





}
